package tools;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

import core.DrawContext;
import core.DrawTool;
import core.Object2D;

public class LineTool extends DrawTool {

	private Point startPoint = new Point();
	
	private Point lastPoint = new Point();
	
	private boolean initSelected = false;
	
	private Color color = Color.black;
	
	private int size = 1;
	
	private LineProxy proxy = new LineProxy();
	
	@Override
	public void processKeyEvent(KeyEvent evt, DrawContext context) {
		// TODO Auto-generated method stub

	}

	@Override
	public void processMouseEvent(MouseEvent evt, DrawContext context) {
	
		switch(evt.getID()){
		case MouseEvent.MOUSE_CLICKED:
			
			if(evt.getButton() == MouseEvent.BUTTON3){
				initSelected = false;
				context.setChanged(true);
			}else if(evt.getButton() == MouseEvent.BUTTON1){
				mouseClick(evt, context);
			}
			
			break;
		case MouseEvent.MOUSE_MOVED:
			mouseMoved(evt, context);
			break;
		}
		
	}
	
	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public Color getColor() {
		return color;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	private void mouseClick(MouseEvent evt, DrawContext ctx){
	
		if(initSelected){
			//Cria a linha
			Graphics2D g2 = (Graphics2D) ctx.getGraphics();
			
			BasicStroke stroke = new BasicStroke(size);
			
			g2.setStroke(stroke);
			g2.setColor(color);
			
			g2.drawLine(
					evt.getX(), 
					evt.getY(),
					(int)startPoint.getX(), 
					(int)startPoint.getY());
			
			
		}
		
		//Seta o inicio da linha
		initSelected = true;
			
		startPoint.x = evt.getX();
		startPoint.y = evt.getY();
		lastPoint.x = startPoint.x;
		lastPoint.y = startPoint.y;
		
			
		ctx.setChanged(true);
	
	}
	
	private void mouseMoved(MouseEvent evt, DrawContext ctx){
		
		if(this.initSelected){
			this.lastPoint.x = evt.getX();
			this.lastPoint.y = evt.getY();
			
			ctx.setChanged(true);
		}
		
	}

	public void init(DrawContext ctx){
		ctx.addObject2d(proxy);
		initSelected = false;
	}
	
	@Override
	public void dispose(DrawContext ctx) {
		ctx.removeObject2d(proxy);
	}
	
	private class LineProxy implements Object2D{

		@Override
		public void draw(Graphics2D g2) {
		
			if(!initSelected){
				return;
			}
			
			BasicStroke stroke = new BasicStroke(size);
			
			g2.setStroke(stroke);
			g2.setColor(color);
			
			g2.drawLine(startPoint.x, startPoint.y, lastPoint.x, lastPoint.y);
		}
		
	}

}
